/**
 * Created by lesonli on 2016/11/17.
 */
import * as types from '../types'
import api from '../../api/modules/config'
import { get_city,get_position } from '../../api/modules/city'

const state = {
    province_list:[],
    city_list: [],
    position_list:[],
    is_loading_list: false
}

// getters
// actions
const actions = {
    get_city_list({ commit }) {
        if (state.city_list.length === 0) {
            commit(types.CITY_LIST_LOADING)
            get_city().then(function (res) {
                if (res.data.res_code === 1) {
                    // res.data.msg.unshift({id:0,name:'全学段'});
                    commit(types.CITY_LIST_LOADED, res.data.msg);
                }
            });
        }

    },
    get_postion_list({ commit }) {
        if (state.position_list.length === 0) {
            commit(types.CITY_LIST_LOADING)
            get_position().then(function (res) {
                if (res.data.res_code === 1) {
                    // res.data.msg.unshift({id:0,name:'全学段'});
                    commit(types.POSITION_LIST_LOADED, res.data.msg);
                }
            });
        }
    }
}
// mutations
const mutations = {
    [types.CITY_LIST_LOADED](state, list) {
        var i;
        for(i=0;i<list.length;i++)
        {
            if(list[i].parent_id === 0)
            {
                list[i].city_list = [];
                state.province_list.push(list[i]);
            }
        }
        for(i=0;i<list.length;i++)
        {
            if(list[i].parent_id !== 0)
            {
                state.city_list.push(list[i]);
                for(var j=0;j<state.province_list.length;j++)
                {
                    if(state.province_list[j].id === list[i].parent_id)
                    {
                        state.province_list[j].city_list.push(list[i]);
                        break;
                    }
                }
            }
        }
        state.is_loading_list = false;
    },
    [types.POSITION_LIST_LOADED](state, list) {
        state.position_list = list;
        state.is_loading_list = false;
    },
    [types.CITY_LIST_LOADING](state) {
        state.is_loading_list = true;
    }
}

export default {
    state,
    actions,
    mutations
}
